﻿using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.Interfaces;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.CT_NBIoT;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.Statistics;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Commons.ViewModels.OwnerMeter;
using Atmk.WaterMeter.MIS.Datas;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Atmk.WaterMeter.MIS.Entities.Models;
using Atmk.WaterMeter.MIS.Logic.IoC;
using Microsoft.CSharp.RuntimeBinder;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;

namespace Atmk.WaterMeter.MIS.Logic
{
    public class OwnerMeterLogic : IOwnerMeterLogic
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();

        private readonly IBaseInfoLogic _baseInfoLogic;

        //private readonly IDistrictLogic _districtLogic;
        private readonly IMapRepository _mapRepository;

        private readonly IMeterReadingRepository _meterReadingRepository;
        private readonly IMeterRepository _meterRepository;
        //private readonly IMeterCodeIdMapRepository _codeIdMapRepository;
        private readonly IOwnerRepository _ownerRepository;
        private readonly IRepository _repository;
        private readonly IStepTariffRepository _stepTariffRepository;
        private readonly IDistrictRepository _districtRepository;

        public OwnerMeterLogic(
            IRepository repository,
            IMeterRepository meterRepository,
            IOwnerRepository ownerRepository,
            IMeterReadingRepository meterReadingRepository,
            IStepTariffRepository stepTariffRepository,
            IMapRepository mapRepository,
            //IMeterCodeIdMapRepository codeIdMapRepository,
            IBaseInfoLogic baseInfoLogic,
        IDistrictRepository districtRepository
        )
        {
            _repository = repository;
            _meterRepository = meterRepository;
            _ownerRepository = ownerRepository;
            _meterReadingRepository = meterReadingRepository;
            _stepTariffRepository = stepTariffRepository;
            _mapRepository = mapRepository;
            _baseInfoLogic = baseInfoLogic;
            _districtRepository = districtRepository;
            //_codeIdMapRepository = codeIdMapRepository;
        }

        /// <summary>
        ///     查询指定区域列表数据
        /// </summary>
        /// <param name="type">0 普通 1 换表</param>
        /// <param name="areaId"></param>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="meterState"></param>
        /// <param name="searchType"></param>
        /// <param name="searchValue"></param>
        /// <returns></returns>
        public object Select(int type, string areaId, string aid, string nodeType, int page, int pageSize, out int count,
            int meterState, string searchType = "", string searchValue = "")
        {
            try
            {
                //获取所有叶子片区信息--临时
                using (var _context = ContextBuilder.Build())
                {
                    List<District> total_districts = null;
                    List<Owner> total_owners = null;
                    List<Meter> total_meters = null;
                    var file = new List<object>();
                    var Projects2district = _context.District.Where(m => m.ProjectId == areaId && m.NodeType == 2).ToList();
                    total_districts = getNodeNext(Projects2district, aid, Projects2district, new List<District>());
                    var districts_ids = total_districts.Select(m1 => m1.Id.ToString());
                    count = _context.Owner.Where(o => districts_ids.Contains(o.DistrictId)).Count();
                    total_owners = _context.Owner.Where(o => districts_ids.Contains(o.DistrictId)).Skip((page - 1) * pageSize).Take(pageSize).ToList();
                    var owners_ids = total_owners.Select(m1 => m1.Id.ToString());
                    total_meters = _context.Meter.Where(m => owners_ids.Contains(m.OwnerId) && m.MeterState != "销户").OrderByDescending(m => m.CreateTime).ToList();
                    //项目水费列表
                    var PrcieSteps = _context.PrcieStep.Where(m => m.ProjectId.ToString() == areaId).ToList();
                    if (meterState > 0)
                    {
                        var meterEnumName = Enum.GetName(typeof(MeterDocumentState), meterState - 1);
                        total_meters = total_meters.Where(m => m.MeterState == meterEnumName).ToList();
                    }

                    //meter = _baseInfoLogic.QuerySearchMeter(searchType, searchValue, total_meters);
                    //拼接
                    //var file = Combination(type, total_districts, total_owners, total_meters, PrcieSteps);
                    for (var i = 0; i < total_owners.Count; i++)
                    {
                        var meters = total_meters.Where(m => m.OwnerId== total_owners[i].Id).ToList();
                        var district = total_districts.First(m => m.Id == total_owners[i].DistrictId);
                        //json转对象
                        var temptest = ((dynamic)JsonConvert.DeserializeObject(total_owners[i].Memo));
                        #region MyRegion
                        //获取坐标类
                        //_mapRepository.CoordinatePoint(owner[0].Id.ToString(), CoordinateType.Owner, out var longitude,
                        // out var latitude, out var elevation);
                        //var mapParameter = mapParameters.FirstOrDefault(m => m.NodeId == owner[0].Id.ToString());
                        //if (mapParameter != null)
                        //{
                        //    longitude = mapParameter.Longitude;
                        //    latitude = mapParameter.Latitude;
                        //    elevation = mapParameter.Elevation;
                        //} 
                        #endregion
                        file.Add(new
                        {
                            districtId = district.Id.ToString(),
                            districtName = district.Name,
                            Owner = new
                            {
                                ownerId = total_owners[i].Id, //业主Id                
                                ownerName = total_owners[i].Name, //业主名称
                                total_owners[i].HouseNumber, //门牌号           
                                mobile = total_owners[i].Mobile, //手机号码
                                longitude=0, //经度 double类型
                                latitude=0, //纬度 double类型
                                elevation=0, //高程(海拔)  double类型
                                ownerMessage = JsonConvert.DeserializeObject(total_owners[i].Memo)
                            },
                            WaterMeter = meters.Count < 1 ? new object() : new
                            {
                                meterId = meters[0].Id, //水表Id
                                MeterType= meters[0].MeterType, //表类型
                                meterNumber = string.Join("<br>", meters.Select(m => m.MeterNumber)), //表编号
                                refillType = meters[0].RefillType, //缴费方式
                                MeterState= meters[0].MeterState, //表状态  
                                priceId = meters[0].PrcieStepId,
                                //priceName = _stepTariffRepository.GetPriceName(meter[i].PrcieStepId),//水价
                                priceName = PrcieSteps.FirstOrDefault(m => m.Id.ToString() == meters[0].PrcieStepId)?.Name,//水价
                                Imei = meters[0].Imei,
                                meterDatas =  new { collector = meters[0].Imei }
                                //meterDatas = string.IsNullOrWhiteSpace(meter[i].Memo)?"":JsonConvert.DeserializeObject(meter[i].Memo)
                            }
                        });
                    }
                    return  file;
                }
            }
            catch (Exception e)
            {
                _logger.Error("业主档案Select方法报错信息：" + e.ToString());
                throw new Exception(e.ToString(), e);
            }
        }

        public object SelectOwner(string ownerid, int page, int pageSize, out int count)
        {
            try
            {
                //获取所有叶子片区信息--临时
                using (var _context = ContextBuilder.Build())
                {
                    Owner owner = _context.Owner.FirstOrDefault(m => m.Id == ownerid);
                    List<Meter> meters = _context.Meter.Where(m => m.OwnerId == ownerid && m.MeterState != "销户").OrderByDescending(m => m.CreateTime).ToList();
                    District district = _context.District.FirstOrDefault(m => m.Id == owner.DistrictId);
                    if (district == null || owner == null)
                    {
                        count = 0;
                        return new object();
                    }
                    //项目水费列表
                    var PrcieSteps = _context.PrcieStep.ToList();
                    //if (meterState > 0)
                    //{
                    //    var meterEnumName = Enum.GetName(typeof(MeterDocumentState), meterState - 1);
                    //    total_meters = total_meters.Where(m => m.MeterState == meterEnumName).ToList();
                    //}
                    var file = new List<object>();
                    foreach (var meter in meters)
                    {
                        //拼接
                        file.Add(new
                        {
                            districtId = district.Id,
                            districtName = district.Name,
                            Owner = new
                            {
                                ownerId = owner.Id, //业主Id                
                                ownerName = owner.Name, //业主名称
                                owner.HouseNumber, //门牌号           
                                mobile = owner.Mobile, //手机号码
                                longitude = 0, //经度 double类型
                                latitude = 0, //纬度 double类型
                                elevation = 0, //高程(海拔)  double类型
                                ownerMessage = JsonConvert.DeserializeObject(owner.Memo)
                            },
                            WaterMeter = new
                            {
                                CtdeviceId = meter.CtdeviceId,
                                meterId = meter.Id, //水表Id
                                meter.MeterType, //表类型
                                meterNumber = meter.MeterNumber, //表编号
                                refillType = meter.RefillType, //缴费方式
                                meter.MeterState, //表状态  
                                priceId = meter.PrcieStepId,
                                //priceName = _stepTariffRepository.GetPriceName(meter[i].PrcieStepId),//水价
                                priceName = PrcieSteps.FirstOrDefault(m => m.Id == meter.PrcieStepId)?.Name,//水价
                                Imei = meter.Imei,
                                meterDatas = new { collector = meter.Imei }
                                //meterDatas = string.IsNullOrWhiteSpace(meter[i].Memo)?"":JsonConvert.DeserializeObject(meter[i].Memo)
                            }
                        });
                    }
                    count = file.Count;
                    //获取分页数据
                    var pageList = PaginatedList<object>.Create(file, page, pageSize);
                    return pageList;
                }
            }
            catch (Exception e)
            {
                _logger.Error("业主档案Select方法报错信息：" + e.ToString());
                throw new Exception(e.ToString(), e);
            }
        }
        public List<District> getNodeNext(List<District> districts, string id, List<District> districtsOld, List<District> result_last_District)
        {
            if (districts.Any(m => m.Id.ToString() == id && m.NodeType == (int)TreeNodeType.last))
            {
                result_last_District.AddRange(districts.Where(m => m.Id.ToString() == id));
            }
            else
            {
                foreach (var item in districtsOld.Where(m => m.Parent == id))
                {
                    getNodeNext(districtsOld.Where(m => m.Parent == id).ToList(), item.Id.ToString(), districtsOld, result_last_District);
                }
            }
            return result_last_District;
        }
        /// <summary>
        ///     换表对外方法
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool Exchange(string uid, dynamic obj)
        {
            try
            {
                var meterNumber = obj.meterNumber.ToString();
                var lastRead = obj.lastRead.ToString();
                var newMeter = obj.newMeter.ToString();
                var value = double.Parse(lastRead);
                return ExchangeLogic(uid, meterNumber, value, newMeter);
            }
            catch (FormatException fe)
            {
                throw new FormatException("新表编号已存在", fe);
            }
            catch (RuntimeBinderException rbe)
            {
                throw new RuntimeBinderException("JObject缺少字段或是空值", rbe);
            }
        }

        /// <summary>
        ///     添加用户和水表信息
        /// </summary>
        /// <param name="districtId"></param>
        /// <param name="owner"></param>
        /// <param name="meter"></param>
        /// <param name="returnOwnerId"></param>
        /// <param name="returnMeterId"></param>
        /// <param name="returnMeterNbId"></param>
        /// <returns></returns>
        public bool InsertOwner(string districtId, dynamic owner, Token token, out string ErrorMessage)
        {
            #region 后期完善-业主水表坐标记录 
            //var longitude = 0.00;
            //var latitude = 0.00;
            //var elevation = 0.00;
            //try
            //{
            //    longitude = Convert.ToDouble(owner.longitude); //Simple.DoubleConvertString(owner.longitude.ToString());
            //    latitude = Convert.ToDouble(owner.latitude);
            //    elevation = Convert.ToDouble(owner.elevation);
            //}
            //catch (Exception e)
            //{
            //    ErrorMessage = e.Message.ToString();
            //    return false;
            //} 
            #endregion
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    //判断 是否新建业主，ownerId 为空则新建业主
                    string ownerId = owner.ownerId.ToString();
                    Owner ownerEntity = null;
                    if (string.IsNullOrWhiteSpace(ownerId))
                    {
                        //接收业主实体
                        ownerEntity = new Owner()
                        {
                            DistrictId = districtId,
                            Name = owner.ownerName.ToString().Trim(),
                            HouseNumber = owner.houseNumber.ToString().Trim(),
                            Mobile = owner.mobile.ToString().Trim(),
                            Memo = owner.ownerMessage.ToString()
                        };
                        if (string.IsNullOrWhiteSpace(ownerEntity.Mobile))
                        {
                            ErrorMessage = "手机号不能为空！";
                            return false;
                        }
                        //如果手机号存在 就返回false
                        if (_context.Owner.FirstOrDefault(m => m.Mobile == ownerEntity.Mobile) != null)
                        {
                            ErrorMessage = "手机号已存在！";
                            return false;
                        }
                        _context.Owner.Add(ownerEntity);
                        //添加业主坐标
                        //_mapRepository.Edit(ownerEntity.Id.ToString(), CoordinateType.Owner, longitude, latitude, elevation);
                    }
                    var result_count = _context.SaveChanges();
                    ErrorMessage = "添加成功";
                    return result_count > 0;
                }
            }
            catch (Exception e)
            {
                _logger.Error(e);
                ErrorMessage = e.Message.ToString();
                return false;
            }
        }

        /// <summary>
        ///     修改业主和水表信息
        /// </summary>
        /// <param name="districtId"></param>
        /// <param name="owner"></param>
        /// <param name="meter"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public bool Update(string districtId, dynamic owner, out Exception exception)
        {
            //TODO:修改水表编号，也需要考虑对应新水表的sim卡的IMEI号的注册情况
            exception = null;
            string ownerId, ownerName, houseNumber, mobile, ownerMessage;
            double longitude, latitude, elevation;

            try
            {
                ownerId = owner.ownerId.ToString();
                ownerName = owner.ownerName.ToString();
                houseNumber = owner.houseNumber.ToString();
                mobile = owner.mobile.ToString();
                ownerMessage = owner.ownerMessage.ToString();
                //修改坐标
                longitude = Simple.DoubleConvertString(owner.longitude.ToString());
                latitude = Simple.DoubleConvertString(owner.latitude.ToString());
                elevation = Simple.DoubleConvertString(owner.elevation.ToString());
                //修改业主数据
                using (var _context = ContextBuilder.Build())
                {
                    var ownerEntity = _context.Owner.First(o => o.Id.ToString() == ownerId);
                    ownerEntity.Name = ownerName;
                    ownerEntity.DistrictId = districtId;
                    ownerEntity.HouseNumber = houseNumber;
                    ownerEntity.Mobile = mobile;
                    ownerEntity.Memo = ownerMessage;
                    _context.Update(ownerEntity);

                    //_mapRepository.Edit(ownerEntity.Id.ToString(), CoordinateType.Owner, longitude, latitude, elevation);

                    return _context.SaveChanges() > 0;
                }
            }
            catch (Exception e)
            {
                exception = e;
                _logger.Error(e);
                return false;
            }
        }

        /// <summary>
        ///     删除水表及用户信息
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="meterId"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public object Delete(string ownerId, string meterId, out Exception exception)
        {
            exception = null;
            try
            {
                var ownerObject = _repository.FindAll<Owner>().ToList();
                var meterObject = _repository.FindAll<Meter>().ToList();
                var judgeOwner = ownerObject.Where(o => o.RecordState == (int)RecordStateEnum.Normal).ToList();
                var judgeMeter = meterObject.Where(o => o.RecordState == (int)RecordStateEnum.Normal).ToList();
                //验证业主和水表存在
                if (judgeOwner.All(d => d.Id.ToString() != ownerId))
                {
                    exception = new Exception("不包含该业主信息，无法删除");
                    return false;
                }

                if (judgeMeter.All(d => d.Id.ToString() != meterId))
                {
                    exception = new Exception("不包含该水表信息，无法删除");
                    return false;
                }

                if (judgeMeter.Count(m => ownerObject.Where(o => o.Id.ToString() == ownerId)
                        .Select(o => o.Id.ToString()).ToList()
                        .Contains(m.OwnerId)) == 1)
                {
                    //当只有一条水表数据时，删除用户数据
                    var owner = ownerObject.First(o => o.Id.ToString() == ownerId);
                    owner.RecordState = RecordStateEnum.Deleted;
                    _repository.Update<Owner>(owner);
                    _mapRepository.Delete(owner.Id.ToString()); //删除坐标
                }

                //删除水表数据
                var meter = meterObject.First(m => m.Id.ToString() == meterId);
                if (RemoveMeter(meter, out exception))
                {
                    //var relations = _codeIdMapRepository.Seletc().Where(c => c.Number == meter.MeterNumber);
                    //if (!relations.Any()) return false;
                    //_ctPlatformDevideManageLogic.DeleteDevice(relations.First().CtNbId);
                    //_codeIdMapRepository.Remove(relations.ToArray());
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                exception = e;
                _logger.Error(e);
                return false;
            }
        }

        /// <inheritdoc />
        public List<Owner> GetOwner(params string[] districtId)
        {
            var dids = districtId.ToArray();
            return _ownerRepository.GetOwners(dids).Where(o => o.RecordState == (int)RecordStateEnum.Normal).ToList();
        }

        /// <summary>
        ///     换表
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="oldMeterNumber"></param>
        /// <param name="lastValue"></param>
        /// <param name="newMeter"></param>
        /// <returns></returns>
        private bool ExchangeLogic(string uid, string oldMeterNumber, double lastValue, dynamic newMeter)
        {
            var objNew = (JObject)JsonConvert.DeserializeObject(newMeter);
            var dic = new Dictionary<string, string>
            {
                ["meterBottomNumber"] = objNew["meterBottomNumber"].ToString(),
                ["dateOfProduction"] = objNew["dateOfProduction"].ToString(),
                ["factoryNumber"] = objNew["factoryNumber"].ToString(),
                ["installDate"] = objNew["installDate"].ToString(),
                ["remark"] = objNew["remark"].ToString()
            };
            //重复表号
            using (var context = Datas.ContextBuilder.Build())
            {
                if (context.Meter.Count(m => m.MeterNumber == objNew["meterNumber"].ToString()) > 0)
                {
                    throw new FormatException("水表号 已存在 不能重复添加同一水表");
                }

                var meterRepository = _meterRepository;
                //获取旧水表
                var oldMeter = context.Meter.FirstOrDefault(m =>
                    m.MeterNumber == oldMeterNumber &&
                    m.MeterState != Enum.GetName(typeof(MeterDocumentState), MeterDocumentState.销户));
                if (oldMeter == null)
                    throw new SqlNullValueException("查不到旧水表数据");

                //根据旧水表获取新的MeterDatas数据
                var oldDatas = oldMeter.Memo;

                var newDatas = GenericsJsonConvert.StringJsonUpdateParam(dic, oldDatas);
                //创建新水表数据
                var meter = new Meter()
                {
                    OwnerId = oldMeter.OwnerId,
                    OldMeterNumber = oldMeter.MeterNumber,
                    MeterNumber = objNew["meterNumber"].ToString(),
                    MeterType = objNew["meterType"].ToString(),
                    MeterState = Enum.GetName(typeof(MeterDocumentState), MeterDocumentState.建档),
                    PrcieStepId = objNew["priceId"].ToString(),
                    RefillType = oldMeter.RefillType,
                    Memo = newDatas
                };
                using (var tran = context.Database.BeginTransaction())
                {
                    try
                    {
                        context.Meter.Add(meter);
                        //销户--水表状态更改
                        //meterRepository.ChangMeterState(oldMeterNumber, MeterDocumentState.销户, uid, "更换水表前销表");
                        var oldmeters = context.Meter.Where(m => m.MeterNumber == oldMeterNumber);
                        foreach (var item in oldmeters)
                        {
                            item.MeterState = "销户";
                            context.Meter.Update(item);
                        }

                        //var ometer = context.Meters.First(m => m.MeterNumber == oldMeterNumber);
                        //ometer.MeterState = "销户";
                        //context.Update(ometer);

                        context.MeterReadingRecord.Add(new MeterReadingRecord()
                        {
                            //Number = meter.MeterNumber,
                            //ReadTime = DateTime.Now,
                            //RecordState = 0,
                            Value = lastValue,
                            //LastValue = lastValue,
                            ValveState = (int)ValveState.Error,
                            //Voltage = 0,
                            //CloseState = 0

                        });
                        //添加水表最后读表记录

                        //_meterReadingRepository.AddRecorcd(meter.MeterNumber, DateTime.Now, lastValue);
                        ////添加水表
                        //if (!AddMeter(meter, out string id, out var ex))
                        //    throw ex; 
                        context.SaveChanges();
                        tran.Commit();
                        return true;
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        return false;
                        // TODO: Handle failure
                    }
                }
            }
        }


        #region 水表查询私有方法

        /// <summary>
        ///     根据类型拼接用户水表信息
        /// </summary>
        /// <param name="type">0 普通 1 换表</param>
        /// <param name="districts"></param>
        /// <param name="owners"></param>
        /// <param name="meter"></param>
        /// <returns></returns>
        private List<object> Combination(int type, IEnumerable<District> districts, List<Owner> owners,
            List<Meter> meter, List<PrcieStep> PrcieSteps)
        {
            //是否换表
            return type == 0
                ? CombinationOwnerMeter(districts, owners, meter, PrcieSteps)
                : CombinationSelsectExchange(districts, owners, meter, PrcieSteps);
        }

        /// <summary>
        ///     换表界面水表信息获取
        /// </summary>
        /// <param name="districts"></param>
        /// <param name="owners"></param>
        /// <param name="meter"></param>
        /// <returns></returns>
        private List<object> CombinationSelsectExchange(IEnumerable<District> districts, List<Owner> owners,
            List<Meter> meter, List<PrcieStep> PrcieSteps)
        {
            var file = new List<object>();
            //马贤辉 新增
            List<MeterReadingRecord> MeterReadingRecord_List;

            var meterNumberList = meter.Select(m1 => m1.MeterNumber);
            using (var context = Datas.ContextBuilder.Build())
            {
                MeterReadingRecord_List = context.MeterReadingRecord.Where(m =>
        meterNumberList.Contains(m.CtdeviceId)).OrderByDescending(m => m.ReadTime).ToList();
            }

            for (var i = 0; i < meter.Count; i++)
            {
                var owner = owners.Where(o => meter[i].OwnerId == o.Id.ToString()).ToList();
                if (owner.Count == 0)
                    continue;
                var district = districts.First(d => owner.Select(o => o.DistrictId).Contains(d.Id.ToString()));
                var address = "";
                long lastSettleRead = 0;

                //马贤辉 新增
                var MeterReadingRecord_temp = MeterReadingRecord_List.FirstOrDefault(m => m.CtdeviceId == meter[i].MeterNumber);
                try
                {
                    address = GenericsJsonConvert.ObjectJsonParament("address", owner[0].Memo);
                    //项oid
                    //lastSettleRead =
                    //    (int) _meterReadingRepository.LastReadingRecord(meter[i].MeterNumber)
                    //        .Value; //TODO:需要确定是否显示详细水表读数，现在先取整数显示
                    lastSettleRead = MeterReadingRecord_temp == null ? 0 : Convert.ToInt64(MeterReadingRecord_temp.Value); //TODO:需要确定是否显示详细水表读数，现在先取整数显示
                }
                catch (SqlNullValueException e)
                {
                    _logger.Error("MeterReadingRepository.LastReadingRecord", e);
                }
                catch (NullReferenceException e)
                {
                    _logger.Error("GenericsJsonConvert.ObjectJsonParament", e);
                }

                file.Add(new
                {
                    districtId = district.Id.ToString(),
                    districtName = district.Name,
                    OwnerId = owner[0].Id, //业主Id                
                    OwnerName = owner[0].Name, //业主名称
                    owner[0].HouseNumber, //门牌号           
                    mobile = owner[0].Mobile, //手机号码
                    address,
                    meterId = meter[i].Id, //水表Id
                    meter[i].MeterType, //表类型
                    meterNumber = meter[i].MeterNumber, //表编号
                    Imei = meter[i].Imei, //表Imei
                    meter[i].MeterState, //表状态  
                    priceId = meter[i].PrcieStepId,
                    //priceName = _stepTariffRepository.GetPriceName(meter[i].PrcieStepId),
                    priceName = PrcieSteps.FirstOrDefault(m => m.Id.ToString() == meter[i].PrcieStepId)?.Name,
                    lastSettleRead
                });
            }
            return file;
        }


        /// <summary>
        ///     获取用户水表json信息
        /// </summary>
        /// <param name="districts"></param>
        /// <param name="owners"></param>
        /// <param name="meter"></param>
        /// <returns></returns>
        private List<object> CombinationOwnerMeter(IEnumerable<District> districts,
            List<Owner> owners,
            List<Meter> meter, List<PrcieStep> PrcieSteps)
        {
            var file = new List<object>();
            double longitude = 0;
            double latitude = 0;
            double elevation = 0;
            List<MapParameter> mapParameters;
            using (var context = ContextBuilder.Build())
            {
                mapParameters = context.MapParameter.ToList();
                //longitude = mapParameterEntity.Longitude;
                //latitude = mapParameterEntity.Latitude;
                //elevation = mapParameterEntity.Elevation;
            }

            //_Context.MapParameter.First(m =>
            //    m.NodeId == nodeid && m.NodeType == coordinateType && m.RecordState == RecordStateEnum.Normal);


            for (var i = 0; i < meter.Count; i++)
            {
                var owner = owners.Where(o => meter[i].OwnerId == o.Id.ToString()).ToList();
                if (owner.Count == 0)
                    continue;
                var district = districts.First(d => owner.Select(o => o.DistrictId).Contains(d.Id.ToString()));
                //获取坐标类
                //_mapRepository.CoordinatePoint(owner[0].Id.ToString(), CoordinateType.Owner, out var longitude,
                // out var latitude, out var elevation);
                var mapParameter = mapParameters.FirstOrDefault(m => m.NodeId == owner[0].Id.ToString());
                if (mapParameter != null)
                {
                    longitude = mapParameter.Longitude;
                    latitude = mapParameter.Latitude;
                    elevation = mapParameter.Elevation;
                }
                file.Add(new
                {
                    districtId = district.Id.ToString(),
                    districtName = district.Name,
                    Owner = new
                    {
                        ownerId = owner[0].Id, //业主Id                
                        ownerName = owner[0].Name, //业主名称
                        owner[0].HouseNumber, //门牌号           
                        mobile = owner[0].Mobile, //手机号码
                        longitude, //经度 double类型
                        latitude, //纬度 double类型
                        elevation, //高程(海拔)  double类型
                        ownerMessage = JsonConvert.DeserializeObject(owner[0].Memo)
                    },
                    WaterMeter = new
                    {
                        meterId = meter[i].Id, //水表Id
                        meter[i].MeterType, //表类型
                        meterNumber = meter[i].MeterNumber, //表编号
                        refillType = meter[i].RefillType, //缴费方式
                        meter[i].MeterState, //表状态  
                        priceId = meter[i].PrcieStepId,
                        //priceName = _stepTariffRepository.GetPriceName(meter[i].PrcieStepId),//水价
                        priceName = PrcieSteps.FirstOrDefault(m => m.Id.ToString() == meter[i].PrcieStepId)?.Name,//水价
                        Imei = meter[i].Imei,
                        meterDatas = new { collector = meter[i].Imei }
                        //meterDatas = string.IsNullOrWhiteSpace(meter[i].Memo)?"":JsonConvert.DeserializeObject(meter[i].Memo)
                    }
                });
            }
            return file.OrderBy(f => JObject.Parse(JsonConvert.SerializeObject(f))["Owner"]["HouseNumber"]).ToList();
            //return file;
        }

        #endregion


        #region 基本业主水表操作

        /// <summary>
        ///     添加业主信息
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        private bool AddOwner(Owner owner, out Exception exception)
        {
            exception = null;
            try
            {
                if (_repository.Add(owner) > 0)
                    return true;
                exception = new Exception("添加业主信息失败");
                return false;
            }
            catch (Exception e)
            {
                _logger.Error(e);
                exception = new Exception($"添加业主信息失败 {e.Message}");
                return false;
            }
        }

        /// <summary>
        ///     移除业主信息
        /// </summary>
        /// <param name="enity"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        private bool RemoveOwner(Owner enity, out Exception exception)
        {
            exception = null;
            try
            {
                var listObject = _repository.FindAll<Owner>().ToList();
                var judge = listObject.Where(o => o.RecordState == (int)RecordStateEnum.Normal).ToList();

                var dis = listObject.First(d => d.Id == enity.Id);
                dis.RecordState = RecordStateEnum.Deleted;
                if (_repository.Update(dis) > 0)
                    return true;
                exception = new Exception("删除业主信息失败");
                return false;
            }
            catch (Exception e)
            {
                _logger.Error(e);
                exception = new Exception($"删除业主信息失败 {e.Message}");
                return false;
            }
        }

        /// <summary>
        ///     移除水表信息
        /// </summary>
        /// <param name="enity"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        private bool RemoveMeter(Meter enity, out Exception exception)
        {
            exception = null;
            try
            {
                var listObject = _repository.FindAll<Meter>().ToList();
                var judge = listObject.Where(o => o.RecordState == RecordStateEnum.Normal).ToList();
                if (judge.Count(d => d.Id == enity.Id) == 0)
                {
                    exception = new Exception("没有可以删除的水表");
                    return false;
                }

                var dis = listObject.First(d => d.Id == enity.Id);
                dis.RecordState = RecordStateEnum.Deleted;
                if (_repository.Update(dis) > 0)
                    return true;
                exception = new Exception("删除水表信息失败");
                return false;
            }
            catch (Exception e)
            {
                _logger.Error(e);
                exception = e;
                return false;
            }
        }

        /// <summary>
        ///     添加水表信息
        /// </summary>
        /// <param name="meter"></param>
        /// <param name="mapId">水表的映射ID</param>
        /// <param name="exception"></param>
        /// <returns></returns>
        //private bool AddMeter(Meter meter, out string mapId, out Exception exception, Token token)
        //{
        //    exception = null;
        //    try
        //    {
        //        //var listObject = Enumerable.ToList<Meter>(_repository.FindAll<Meter>());
        //        //var judge = listObject.Where(o => o.RecordState == RecordStateEnum.Normal).ToList();

        //        //CommTypeFilter(meter, out mapId); //根据水表的通讯类型做相应的处理
        //        switch (meter.CommType)
        //        {
        //            case "CT_NB":
        //                var imei = GenericsJsonConvert.ObjectJsonParament("collector", meter.Memo);
        //                mapId = CreatNBEntityTOCTNB(meter, imei);
        //                SaveNBId(meter.MeterNumber, mapId, imei);
        //                break;
        //        }
        //        if (_repository.Add(meter) > 0)
        //            return true;
        //        exception = new Exception("添加水表信息失败");
        //        return false;
        //    }
        //    catch (Exception e)
        //    {
        //        mapId = "";
        //        _logger.Error(e);
        //        exception = e;
        //        return false;
        //    }
        //}

        /// <summary>
        ///     销表
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="cancelMeter"></param>
        /// <returns></returns>
        public bool Cancel(string uid, CancelMeter cancelMeter)
        {
            //获取水表
            //var meters = _meterRepository.FindAll<Meter>().Where(m =>
            //    m.MeterNumber == cancelMeter.meterNumber &&
            //    m.MeterState != Enum.GetName(typeof(MeterDocumentState), MeterDocumentState.销户)).ToList();
            //if (!meters.Any())
            //{
            //    _logger.Warn("查不到水表数据");
            //    return false;
            //}
            using (var context = Datas.ContextBuilder.Build())
            {
                var meter = context.Meter.FirstOrDefault(m => m.MeterNumber == cancelMeter.meterNumber);
                if (meter != null)
                {
                    meter.MeterState = "销户";
                    context.Update(meter);
                }
                context.MeterReadingRecord.Add(new MeterReadingRecord()
                {
                    //Number = meter.MeterNumber,
                    ReadTime = DateTime.Now,
                    //RecordState = 0,
                    Value = cancelMeter.lastRead,
                    //LastValue = cancelMeter.lastRead,
                    ValveState = (int)ValveState.Opening,
                    //Voltage = 0,
                    //CloseState = 0,
                    //MeterID= meter.Id.ToString(),
                    MsgType = 4,
                    //Value24Type = (int)Value24Type.four  //销表
                });
                return context.SaveChanges() > 0;
            }
            //销户--水表状态更改
            //_meterRepository.ChangMeterState(cancelMeter.meterNumber, MeterDocumentState.销户, uid, cancelMeter.remark);
            //添加水表最后读表记录
            //_meterReadingRepository.AddRecorcd(cancelMeter.meterNumber, DateTime.Now, cancelMeter.lastRead);
            //return true;
        }

        #endregion

    }
}